package com.springMVC.demo;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/hello")
public class HelloController {
    //@GetMapping("/hello1")和下面一行是一样的
    @RequestMapping(value = "/test1",method = RequestMethod.GET)
    public String test1(String str){
        return "str = " + str;
    }
    //@GetMapping("/hello2")和下面一行是一样的
    @RequestMapping(value = "/test2",method = RequestMethod.POST)
    public String test2(Integer age,Boolean flag){//?age=aaa&flag=2 or ?age=18&flag=1 or ?age=18&flag=true
        return "age = " + age + ",flag = " + flag;
    }
    //可以使用POST、GET两种请求方式
    @RequestMapping(value = "/test3",method = {RequestMethod.GET,RequestMethod.POST})
    public String test3(Person person){
        return person.toString();
    }
    @RequestMapping("/test4")
    public Boolean test4(){
        return true;
    }
    @RequestMapping("/test5")
    //前端使用sa就代表后端的name，需要传?sa=xxx，?name=xxx也是无法访问的
    public String test5(@RequestParam("sa") String name){
        //前后端变量名不一致的时候使用@RequestParam("xxx")注释
        return "name = "+name;
    }
    @RequestMapping("/test6")
    //可以不用传入sa，但当没有传入sa的值时，name则为null（包括传入?name=xxx）
    public String test6(@RequestParam(value = "sa",required = false) String name){
        return "name = "+name;
    }
    @RequestMapping("/test7")
    public int test7(int age){//不能传入null，否则报错
        return age;
    }
    @RequestMapping("test8")
    public String test8(String[] str){
        return Arrays.toString(str);
    }
    @RequestMapping("/test9")
    public String test9(@RequestParam List<String> list){
        //List的时候，需要加上@RequestParam注释
        return list.toString();
    }
    @RequestMapping("/test10")
    public String test10(@RequestBody Person person){//将HTTP中的请求正文转化为Person对象
        return person.toString();
    }
    //从URL中获取参数
    @RequestMapping("/{Id}")
    public Integer test11(@PathVariable("Id") Integer articleId){
        return articleId;
    }
    //文件上传
    @RequestMapping("/test12")
    public String test12(@RequestPart("newFileName") MultipartFile file) throws IOException {
        System.out.println("ContentType: "+file.getContentType());
        System.out.println("OriginalFilename: "+file.getOriginalFilename());
        file.transferTo(new File("D:\\TestFile(delete)\\Test\\Test.txt"));
        return "name = "+file.getName();
    }
}
